﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using RENIT.WebParts.TagsCloud3D.Controls;
using RENIT.TagsCloud3D.Utils;
using Microsoft.SharePoint.Portal.WebControls;
using Microsoft.Office.Server.SocialData;
using System.Xml.Serialization;

namespace RENIT.WebParts.TagsCloud3D
{
    [ToolboxItemAttribute(false)]
    [XmlRoot(Namespace="http://renaissance-it.ru/")]
    public class TagsCloud3DWebPart : TagCloudWebPart
    {
        private TagsCloud3DView view;

        private TypeWrapper<TagCloudWebPart> wrapper;

        private TagCloudItem[] items;

        public TagsCloud3DWebPart()
        {
            wrapper = new TypeWrapper<TagCloudWebPart>(this);
            Width = Constants.Width;
            Height = Constants.Height;
        }

       
        protected override void CreateChildControls()
        {
            try
            {
                view = Page.LoadControl(Constants.TagsCloud3DAscxPath) as TagsCloud3DView;
            }
            catch(Exception err)
            {
                Controls.Add(new Literal { Text = string.Format("<h1>Error</h1><p>{0}</p>", err.ToString().Replace(Environment.NewLine, "<br />")) });
                return;
            }
            view.Width = Width;
            view.Height = Height;
            view.Tags = GetTags();
            Controls.Add(view);
        }
        
        private TagCloudItem[] GetTags()
        {
            if (items == null || items.Length == 0)
            {

                wrapper.InvokeNonPublic("EnsureDataAvailable", null);
                var terms = wrapper.TryGetPropertyValue<SocialTerm[]>("Terms");
                items = GetTagCloudItemsFromSocialTerms(terms);
            }
            return items;
        }

        protected virtual bool RenderCloudsView(HtmlTextWriter htw)
        {
            view.Tags = GetTags();
            if (GetTags() == null || GetTags().Length == 0)
            {
                return false;
            }
            else
            {
                view.RenderControl(htw);
                return true;
            }
        }
        
        protected override void RenderWebPart(HtmlTextWriter htw)
        {
            if (!RenderCloudsView(htw))
            {
                base.RenderWebPart(htw);
            }
        }
        
        protected override void RenderChildren(HtmlTextWriter writer)
        {
            if (!RenderCloudsView(writer))
            {
                view.Visible = false;
                base.RenderChildren(writer);
            }
        }
        
    }
}
